/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 5.5.2011, 14:04:17
 */

package GUI;


import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.dbcp.BasicDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
import Model.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author pyty
 */
public class MainFrame extends javax.swing.JFrame {

    MediumTableModel mediumModel;
    ClientTableModel clientModel;
    //Locale locale = Config.LOCALE;
    //ResourceBundle texts = ResourceBundle.getBundle(Config.TEXTS_FILE, locale);
    
    //java.util.ResourceBundle texts = java.util.ResourceBundle.getBundle("i18n/texts");
    private LoadMediumsSwingWorker loadMediumsSwingWorker;
    private AddMediumSwingWorker addMediumSwingWorker;
    private EditMediumSwingWorker editMediumSwingWorker;
    private DeleteMediumSwingWorker deleteMediumSwingWorker;

    private LoadClientsSwingWorker loadClientsSwingWorker;
    private AddClientSwingWorker addClientSwingWorker;
    private EditClientSwingWorker editClientSwingWorker;
    private DeleteClientSwingWorker deleteClientSwingWorker;
    
    MediumManagerImpl mediumManager = new MediumManagerImpl();
    ClientManagerImpl clientManager = new ClientManagerImpl();
    BorrowManagerImpl borrowManager = new BorrowManagerImpl();
    
    private static final Logger logger = Logger.getLogger(
            MainFrame.class.getName());
 
    private class LoadMediumsSwingWorker extends SwingWorker<List<Medium>,Void> {

        private String searchString = null;
        
        @Override    
        protected List<Medium> doInBackground() throws Exception {
            
            try {
                DataSource ds = prepareDataSource();
                mediumManager.setDataSource(ds);
                List<Medium> mediums;
                if(searchString == null) {
                    mediums = mediumManager.findAllMediums();
                } else {
                    mediums = mediumManager.searchMediumsByString(searchString);
                }
                return mediums;
//                for(Medium m : mediums) {
//                    mediumModel.addMedium(m);
//                }
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }
        
        @Override    
        protected void done() {
            try {
                //jTextArea.append("Result is: " + get() + "\n");
                List<Medium> mediums = get();
                mediumModel.removeAll();
            
                for(Medium m : mediums) {
                    mediumModel.addMedium(m);
                }
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }  
        
        public void setSearchString(String s) {
            this.searchString = s;
        }
    }
    
    private class AddMediumSwingWorker extends SwingWorker<Medium,Void> {
        private Medium medium = null;
        
        public void setMedium(Medium medium) {
            this.medium = medium;
        }

        @Override    
        protected Medium doInBackground() throws Exception {
            try {
                DataSource ds = prepareDataSource();
                mediumManager.setDataSource(ds);
                mediumManager.createMedium(medium);
                return medium;
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }
        
        @Override    
        protected void done() {
            try {
                //jTextArea.append("Result is: " + get() + "\n");
                //Medium medium = get();
                mediumModel.addMedium(get());
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }        
    }
    
    private class EditMediumSwingWorker extends SwingWorker<Medium,Void> {
        private Medium medium = null;
        
        public void setMedium(Medium medium) {
            this.medium = medium;
        }

        @Override    
        protected Medium doInBackground() throws Exception {
            try {
                DataSource ds = prepareDataSource();
                mediumManager.setDataSource(ds);
                mediumManager.updateMedium(medium);
                return medium;
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }
        
        @Override    
        protected void done() {
            try {
                //jTextArea.append("Result is: " + get() + "\n");
                Medium medium = get();
                //mediumModel.fireTableRowsUpdated(ERROR, ERROR);
                mediumModel.fireTableDataChanged();
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }        
    }
    
    private class DeleteMediumSwingWorker extends SwingWorker<Medium,Void> {
        private Medium medium = null;
        
        public void setMedium(Medium medium) {
            this.medium = medium;
        }
        
        @Override    
        protected Medium doInBackground() throws Exception {
            
            try {
                DataSource ds = prepareDataSource();
                mediumManager.setDataSource(ds);
                mediumManager.deleteMedium(medium);
                return medium;
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }
        
        @Override    
        protected void done() {
            try {
                //Medium medium = get();
                mediumModel.deleteValue(get());
                
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        } 
    }
    
    private class LoadClientsSwingWorker extends SwingWorker<List<Client>,Void> {

        private String searchString = null;

        @Override
        protected List<Client> doInBackground() throws Exception {

            try {
                DataSource ds = prepareDataSource();
                clientManager.setDataSource(ds);
                List<Client> clients;
                if(searchString == null) {
                    clients = clientManager.findAllClients();
                } else {
                    clients = clientManager.searchClientsByString(searchString);
                }
                return clients;
//                for(Client client : clients) {
//                    mediumModel.addClient(m);
//                }
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }

        @Override
        protected void done() {
            try {
                //jTextArea.append("Result is: " + get() + "\n");
                List<Client> clients = get();
                clientModel.removeAll();

                for(Client c : clients) {
                    clientModel.addClient(c);
                }
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }

        public void setSearchString(String s) {
            this.searchString = s;
        }
    }

    private class AddClientSwingWorker extends SwingWorker<Client,Void> {
        private Client client = null;

        public void setClient(Client client) {
            this.client = client;
        }

        @Override
        protected Client doInBackground() throws Exception {
            try {
                DataSource ds = prepareDataSource();
                clientManager.setDataSource(ds);
                clientManager.createClient(client);                
                return client;
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }

        @Override
        protected void done() {
            try {
                //jTextArea.append("Result is: " + get() + "\n");
                //Client client = get();
                clientModel.addClient(get());
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }
    }
   private class EditClientSwingWorker extends SwingWorker<Client,Void> {
        private Client client = null;
        
        public void setClient(Client client) {
            this.client = client;
        }

        @Override    
        protected Client doInBackground() throws Exception {
            try {
                DataSource ds = prepareDataSource();
                clientManager.setDataSource(ds);
                clientManager.updateClient(client);
                return client;
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }
        
        @Override    
        protected void done() {
            try {
                
                Client client = get();
                
                clientModel.fireTableDataChanged();
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }        
    }
   
    private class DeleteClientSwingWorker extends SwingWorker<Client,Void> {
        private Client client = null;

        public void setClient(Client client) {
            this.client = client;
        }

        @Override
        protected Client doInBackground() throws Exception {

            try {
                DataSource ds = prepareDataSource();
                clientManager.setDataSource(ds);
                clientManager.deleteClient(client);
                return client;
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }

        @Override
        protected void done() {
            try {
                //Client client = get();
                clientModel.deleteValue(get());

            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }
    }

    public void addMedium(Medium medium) {
        addMediumSwingWorker = new AddMediumSwingWorker();
        addMediumSwingWorker.setMedium(medium);
        addMediumSwingWorker.execute();
    }
    public void addClient(Client client) {
        addClientSwingWorker = new AddClientSwingWorker();
        addClientSwingWorker.setClient(client);
        addClientSwingWorker.execute();
    }
    
    public void editMedium(Medium medium) {
        editMediumSwingWorker = new EditMediumSwingWorker();
        editMediumSwingWorker.setMedium(medium);
        editMediumSwingWorker.execute();
    }
    public void editClient(Client client) {
        editClientSwingWorker = new EditClientSwingWorker();
        editClientSwingWorker.setClient(client);
        editClientSwingWorker.execute();
    }

    public static DataSource prepareDataSource() throws SQLException { 
        DBConfig dbConfig = new DBConfig();
        
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(dbConfig.getDbUrl());
        ds.setUsername(dbConfig.getDbUser());
        ds.setPassword(dbConfig.getDbPass());
        
        ds.setDriverClassName(dbConfig.getDbDriver());

        return ds;
    }
    
    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        
        /*mediumModel = (MediumTableModel) jTableMediums.getModel();
        ClientTableModel clientModel = (ClientTableModel) jTableClients.getModel();
        /*try {
            model.getTableFromDB();
        } catch (SQLException ex) {
            throw new RuntimeException("DB Error",ex);
        }*/
      
        /*try {
            DataSource ds = prepareDataSource();
            MediumManagerImpl mediumManager = new MediumManagerImpl();
            mediumManager.setDataSource(ds);
            List<Medium> mediums = mediumManager.findAllMediums();
            
            for(Medium m : mediums) {
                mediumModel.addMedium(m);
            }
            ClientManagerImpl clientManager = new ClientManagerImpl();
            clientManager.setDataSource(ds);
            List<Client> clients = clientManager.findAllClients();

            for(Client c : clients) {
                clientModel.addClient(c);
            }
            
        } catch (SQLException ex) {
            throw new RuntimeException("DB Error",ex);
        } */
        
        mediumModel = (MediumTableModel) jTableMediums.getModel();
        clientModel = (ClientTableModel) jTableClients.getModel();
        /*try {
            model.getTableFromDB();
        } catch (SQLException ex) {
            throw new RuntimeException("DB Error",ex);
        }*/
      
        //try {
            //DataSource ds = prepareDataSource();
            loadMediumsSwingWorker = new LoadMediumsSwingWorker();
            loadMediumsSwingWorker.execute();


            loadClientsSwingWorker = new LoadClientsSwingWorker();
            loadClientsSwingWorker.execute();

    }
    
    public MediumManagerImpl getMediumManager(){
        return mediumManager;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableMediums = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton9 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        addClient = new javax.swing.JButton();
        editClient = new javax.swing.JButton();
        deleteClient = new javax.swing.JButton();
        showAllBorrows = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableClients = new javax.swing.JTable();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jButton10 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("i18n/texts"); // NOI18N
        setTitle(bundle.getString("MainFrame.title")); // NOI18N
        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(700, 590));

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jPanel1.setToolTipText(bundle.getString("mediumManager")); // NOI18N

        jTableMediums.setModel(new MediumTableModel());
        jTableMediums.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTableMediums.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTableMediumsMouseReleased(evt);
            }
        });
        jTableMediums.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                del(evt);
            }
        });
        jScrollPane1.setViewportView(jTableMediums);

        jButton1.setText(bundle.getString("addMedium")); // NOI18N
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setMaximumSize(new java.awt.Dimension(103, 23));
        jButton1.setMinimumSize(new java.awt.Dimension(103, 23));
        jButton1.setPreferredSize(new java.awt.Dimension(110, 23));
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(bundle.getString("editMedium")); // NOI18N
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setMinimumSize(new java.awt.Dimension(103, 23));
        jButton2.setPreferredSize(new java.awt.Dimension(110, 23));
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText(bundle.getString("deleteMedium")); // NOI18N
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setPreferredSize(new java.awt.Dimension(110, 23));
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText(bundle.getString("borrowToAClient")); // NOI18N
        jButton4.setFocusable(false);
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel1.setText(bundle.getString("search")); // NOI18N

        jButton9.setText(bundle.getString("search")); // NOI18N
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton9)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 806, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton9)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 491, Short.MAX_VALUE))
        );

        jButton4.setVisible(false);

        jTabbedPane1.addTab(bundle.getString("mediumManager"), jPanel1); // NOI18N

        jPanel2.setToolTipText(bundle.getString("clientManager")); // NOI18N

        addClient.setText(bundle.getString("addClient")); // NOI18N
        addClient.setFocusable(false);
        addClient.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addClient.setMaximumSize(new java.awt.Dimension(103, 23));
        addClient.setMinimumSize(new java.awt.Dimension(103, 23));
        addClient.setPreferredSize(new java.awt.Dimension(110, 23));
        addClient.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        addClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addClientActionPerformed(evt);
            }
        });

        editClient.setText(bundle.getString("editClient")); // NOI18N
        editClient.setFocusable(false);
        editClient.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        editClient.setMaximumSize(new java.awt.Dimension(110, 23));
        editClient.setMinimumSize(new java.awt.Dimension(110, 23));
        editClient.setPreferredSize(new java.awt.Dimension(110, 23));
        editClient.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        editClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editClientActionPerformed(evt);
            }
        });

        deleteClient.setText(bundle.getString("deleteClient")); // NOI18N
        deleteClient.setFocusable(false);
        deleteClient.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        deleteClient.setMaximumSize(new java.awt.Dimension(110, 23));
        deleteClient.setMinimumSize(new java.awt.Dimension(110, 23));
        deleteClient.setPreferredSize(new java.awt.Dimension(110, 23));
        deleteClient.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        deleteClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteClientActionPerformed(evt);
            }
        });

        showAllBorrows.setText(bundle.getString("showAllBorrows")); // NOI18N
        showAllBorrows.setFocusable(false);
        showAllBorrows.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        showAllBorrows.setMaximumSize(new java.awt.Dimension(103, 23));
        showAllBorrows.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        showAllBorrows.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showAllBorrowsActionPerformed(evt);
            }
        });

        jTableClients.setModel(new ClientTableModel());
        jTableClients.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(jTableClients);

        jLabel2.setText(bundle.getString("MainFrame.jLabel2.text")); // NOI18N

        jButton10.setText(bundle.getString("MainFrame.jButton10.text")); // NOI18N
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addClient, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(editClient, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteClient, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(showAllBorrows, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 76, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton10)
                .addContainerGap())
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 806, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(addClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(editClient, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(deleteClient, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton10)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(showAllBorrows, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab(bundle.getString("clientManager"), jPanel2); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 811, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
         MediumActionDialog dialog = new MediumActionDialog(this, true);
       //  logger.log(Level.ALL, "Pressed AddMedium button");
         dialog.setVisible(true);
         
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTableMediumsMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableMediumsMouseReleased
    }//GEN-LAST:event_jTableMediumsMouseReleased

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (jTableMediums.getSelectedRowCount() != 0) {
            Integer row = jTableMediums.getSelectedRow();
            Medium medium = mediumModel.getValueAt(row);

            MediumActionDialog dialog = new MediumActionDialog(this, true, medium);
            dialog.setMedium(medium);
            dialog.disableButton();


            dialog.setVisible(true);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        if (jTableMediums.getSelectedRowCount() != 0) {
            Integer row = jTableMediums.getSelectedRow();
            Medium medium = mediumModel.getValueAt(row);
            
            ClientChooserDialog dialog = new ClientChooserDialog(this, true);
            dialog.setMedium(medium);
            dialog.setVisible(true);
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void addClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClientActionPerformed
        ClientActionDialog dialog = new ClientActionDialog(this, true);
      //  logger.log(Level.ALL, "Pressed AddClient button");
        dialog.setVisible(true);
}//GEN-LAST:event_addClientActionPerformed

    private void editClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editClientActionPerformed
        if (jTableClients.getSelectedRowCount() != 0) {
            Integer row = jTableClients.getSelectedRow();
            Client client = clientModel.getValueAt(row);

            ClientActionDialog dialog = new ClientActionDialog(this, true, client);
            dialog.setClient(client);
        //    logger.log(Level.ALL, "Pressed EditClient button", client);


            dialog.setVisible(true);
        }
}//GEN-LAST:event_editClientActionPerformed

    private void showAllBorrowsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showAllBorrowsActionPerformed
        if (jTableClients.getSelectedRowCount() != 0) {
            Integer row = jTableClients.getSelectedRow();
            Client client = clientModel.getValueAt(row);

            ShowBorrowsDialog dialog = new ShowBorrowsDialog(this, true, client);
            dialog.setBorrows(client);
        //    logger.log(Level.ALL, "Pressed ShowAllBorrows button", client);


            dialog.setVisible(true);
        }
}//GEN-LAST:event_showAllBorrowsActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
       if (jTableMediums.getSelectedRowCount() != 0) {
            int reply = JOptionPane.showConfirmDialog(this, RBUtils.getBoundle("deleteConfirm"), RBUtils.getBoundle("Warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (reply == JOptionPane.YES_OPTION) {
                Integer row = jTableMediums.getSelectedRow();
                Medium medium = mediumModel.getValueAt(row);
                deleteMediumSwingWorker = new DeleteMediumSwingWorker();
                deleteMediumSwingWorker.setMedium(medium);
                deleteMediumSwingWorker.execute();
            }
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void del(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_del
        if(evt.getKeyCode() == 127 && jTableMediums.getRowCount() != 0) {
            jButton3ActionPerformed(null);
        }
    }//GEN-LAST:event_del

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
        loadMediumsSwingWorker = new LoadMediumsSwingWorker();
        loadMediumsSwingWorker.setSearchString(jTextField1.getText().toLowerCase());
        loadMediumsSwingWorker.execute();
    }//GEN-LAST:event_jButton9ActionPerformed

    private void deleteClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteClientActionPerformed
       if (jTableClients.getSelectedRowCount() != 0) {
            int reply = JOptionPane.showConfirmDialog(this, RBUtils.getBoundle("deleteClientConfirm"), RBUtils.getBoundle("Warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (reply == JOptionPane.YES_OPTION) {                                
                Integer row = jTableClients.getSelectedRow();
                Client client = clientModel.getValueAt(row);
                List<Medium> mediums;
            try {
                DataSource ds = prepareDataSource();
                borrowManager.setDataSource(ds);
                                
                
                mediums = (List<Medium>)borrowManager.getMediumsBorrovedByClient(client);                                

            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
                if (mediums.isEmpty()){
                deleteClientSwingWorker = new DeleteClientSwingWorker();
                deleteClientSwingWorker.setClient(client);
                deleteClientSwingWorker.execute();
           //     logger.log(Level.ALL, "Pressed DeleteClient button", client);
                }else{
            //        logger.log(Level.ALL, "Attemp to delete a client with borrows", client);
                    JOptionPane.showMessageDialog(this, RBUtils.getBoundle("cantDeleteClient"));
                }
                
            }
       }
    }//GEN-LAST:event_deleteClientActionPerformed

    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
        loadClientsSwingWorker = new LoadClientsSwingWorker();
        loadClientsSwingWorker.setSearchString(jTextField2.getText().toLowerCase());
        loadClientsSwingWorker.execute();
    }//GEN-LAST:event_jButton10ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) throws SQLException{
        try {
	    // Set System L&F
            UIManager.setLookAndFeel(
            UIManager.getSystemLookAndFeelClassName());
        } 
        catch (UnsupportedLookAndFeelException e) {
            // handle exception
        }
        catch (ClassNotFoundException e) {
            // handle exception
        }
        catch (InstantiationException e) {
            // handle exception
        }
        catch (IllegalAccessException e) {
            // handle exception
        }
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                MainFrame window = new MainFrame();
                window.setVisible(true);
                window.setLocationRelativeTo(null);
                //JOptionPane.showMessageDialog(null," Message",  "Error",  JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addClient;
    private javax.swing.JButton deleteClient;
    private javax.swing.JButton editClient;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton9;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTableClients;
    private javax.swing.JTable jTableMediums;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JButton showAllBorrows;
    // End of variables declaration//GEN-END:variables

}
